//
//  MTZDiscoverSearchView.swift
//  weibomtz
//
//  Created by 毛铁柱 on 16/10/16.
//  Copyright © 2016年 mtz. All rights reserved.
//

import UIKit

class MTZDiscoverSearchView: UIView {

    @IBOutlet weak var textFieldRightCons: NSLayoutConstraint!
    //取消按钮
    @IBOutlet weak var cancelButton: UIButton!
    
    @IBOutlet weak var textField: UITextField!
    
    //从xib里面加载view
    
    class func searchView() -> MTZDiscoverSearchView{
    
    return NSBundle.mainBundle().loadNibNamed("MTZDiscoverSearchView", owner: nil, options: nil).last! as! MTZDiscoverSearchView
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func awakeFromNib() {
        textField.leftView = leftView
        textField.leftViewMode = .Always
        
//        // 设置边线
//        textField.layer.borderWidth = 2
//        textField.layer.borderColor = UIColor.redColor().CGColor
//        
//        // 设置圆角
//        textField.layer.cornerRadius = 5
//        textField.layer.masksToBounds = true
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        leftView.frame.size = CGSize(width: frame.height, height: frame.height)
    }

    // textField开始编辑的时候执行的方法
    
    @IBAction func textFieldDidBegin(sender: UITextField) {
        print("开始编辑了")
        // 1.更新右边的约束
        self.textFieldRightCons.constant = self.cancelButton.frame.width
        // 2.调用layoutIfNeeded并且将其放在动画的block中
        UIView.animateWithDuration(1) {
            
//            // 设置需要重新布局(系统会在合适的时候去布局)
//            sender.setNeedsLayout()
            //如果需要重新布局立马执行
            sender.layoutIfNeeded()
        }
    }
    
    //取消按钮点击
    
    @IBAction func cancelButtonClick(sender: UIButton) {
        self.textFieldRightCons.constant = 0
        UIView.animateWithDuration(1) { 
            self.textField.layoutIfNeeded()
        }
        self.textField.resignFirstResponder()
    }
    
    //懒加载控件
    private lazy var leftView:UIImageView = {
        let imageView = UIImageView(image: UIImage(named:"searchbar_textfield_search_icon"))
        //设置图片填充模式
        imageView.contentMode = .Center
        return imageView
    
    }()
    
    
    
}


